
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()

var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(data) {
    let url = 'https://api.wenfree.cn/?s=App.Autojs_Tiktok.Spiders'
    var headers = {
        "Content-Type": "application/json"
    };
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data);
        return data;
    }
};


function getTitleConent(){
    if ( currentActivity() == "com.wudaokou.hippo.search.SearchActivity" ){
        log("进入搜索界面")
        //没有分类就返回
        if ( !appInfo.category){
            return true;
        }

        try {
            appInfo['search_key'] = id("tv_search_editable_keyword").findOne(200).text()

            let allprice = textMatches("¥.*").find();
            // log(allprice[0].text())
            for (let i=0;i<allprice.length;i++){
                let price = allprice[i].text()
                
                // 假设 allprice[i] 是当前元素，获取其兄弟节点的 text 内容作为 title
                function getTitle(objects){
                    let siblings = objects.parent().children();
                    let title = '';
                    for (let j = 0; j < siblings.length; j++) {
                        let siblingText = siblings[j].text();
                        if (siblingText.length > 6) {
                            title += siblingText + ' ';
                            return title.trim();
                        }
                    }
                }
                let title = getTitle(allprice[i]);
                log(title, price)
        
                var postData = {
                    "city": "北京",
                    "local": appInfo.local,
                    "category": appInfo.category,
                    "category2": appInfo.category2,
                    "search_key": appInfo['search_key'],
                    "title": title,
                };
                
                if (price.includes('/')) {
                    postData['price'] = price;
                } else {
                    postData['vip'] = price;
                }
                f.postJson(postData)
            }
        }catch (error) {
            log('获取标题内容失败', error);
        }
        
        if (f.ms({"textMatches":"还有.*个已售完商品"}, true ) ){
            //这里要把这个点开
        }else
        if( f.ms({"textMatches":"我可是有底线的哦||正在加载更多||RECOMMEND"}) ){
            return true
        }
    
        f.moveTo(0.5,0.8,0.5,0.5,1000)
    }
}





// if (getTitleConent()) {
//     back();
// }

var appInfo = {
    search_word: '',
    shop: '',
    categories: '',
    name: '',
    price: '',
    price_old: '',
    author: '',
    rate: '',
    sold: '',
    mintitle: '',
    alltitle: '',
    rank: '',
    link: '',
    fav: '',
    tag: '',
}
var storage = storages.create("tiktok");
var look = []
look = storage.get("look") || [];
// storage.remove("look");
log(look)


f.active("com.zhiliaoapp.musically", 5)


//批查打印app参数
function printAll(ways) {
    if (!ways) {
        ways = 'className'
    }
    if (ways = 'className') {
        var all_Info = classNameMatches(/.*/).find();
    } else
        if (ways == 'text') {
            var all_Info = textMatches(/.*/).find();
        } else
            if (ways == 'id') {
                var all_Info = idMatches(/.*/).find();
            } else {
                eval('var all_Info = ' + ways + '.find();')
            }

    if (all_Info) {
        for (var i = 0; i < all_Info.length; i++) {
            var d = all_Info[i];
            log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"',
                "clickable->" + d.clickable(), 'selected->' + selected(), "depth->" + d.depth(),
                d.bounds().centerX(), d.bounds().centerY())
        }
    } else {
        log('没有找到任何相关的节点')
    }
}


// printAll()

var used_price = []


function prudcuts_list() {
    let titles = className("com.lynx.tasm.behavior.ui.text.FlattenUIText").boundsInside(0, 0, device.width, device.height).find();
    if (titles) {
        for (let i = 0; i < titles.length; i++) {
            let title = titles[i].text()
            if (title.length < 20) {
                continue;
            }
            if (!used_price.includes(title) && !title.includes('$')) {
                used_price.push(title)
                f.clickObj(titles[i], 5, title)
                return true;
            }
        }
        f.moveTo(0.5, 0.8, 0.5, 0.5, 1000)
        sleep(5000)
    }
}


function getOne(){
    try {
        appInfo['shop'] = id("tgc").findOne(200).text()
    } catch (error) {
        log('获取店铺失败', error);
        return 
    }
    

    var title = textMatches(".*…").findOne(200);
    if( title   ){
        f.clickObj(title, 1, '点击更多')
        log('等待变化')
    }

    var texts = className("com.lynx.tasm.behavior.ui.text.FlattenUIText").find()
    if(texts){
        var prudcuts = {}
        var price_key = true
        var tag_key = false

        for (let i=0;i<texts.length;i++){
            var text = texts[i].text()
            if( text ){
                log(text)
                if( tag_key ){
                    prudcuts['tag'] = prudcuts['tag'] ? prudcuts['tag'] + '|' + text : text
                    continue;
                }
                if(  text.includes('%')){
                    prudcuts['rate'] = text
                }
                if (price_key && text.includes('$')){
                    prudcuts['price'] = text
                    price_key = false
                }
                if (text.includes('$') && !price_key ){
                    prudcuts['price_old'] = text
                }
                if( text.length > 20 ){
                    prudcuts['title'] = text
                }
                if( text.includes('by') ){
                    prudcuts['author'] = text
                }
                if( text.includes('(') ){
                    prudcuts['fav'] = text
                    prudcuts['rank'] = texts[i-1].text()
                }
                if( text.endsWith('sold') ){
                    prudcuts['sold'] = text
                    tag_key = true
                }
            }
        }
    }
    // if (f.ms({ 'desc': 'Share' }, true, 3, '分享按钮')){
    //     f.ms({ 'textMatches' : 'Copy link' },true, 3, '复制链接')
    //     f.active("org.fd.ffdd.v7", 3)
    //     var link = getClip()
    //     if (link){
    //         log('获取到链接', link)
    //         prudcuts['link'] = link
    //     }
    //     f.active("com.zhiliaoapp.musically", 3)
    // }

    // console.show()
    prudcuts['shop'] = appInfo['shop']
    log(prudcuts)
    f.postJson(prudcuts)
    return true

}
// let objs = text("Copy link").findOne(200);
// log(objs.text())
// getOne()

// if (currentActivity() == "com.bytedance.hybrid.spark.page.SparkActivity" ){
//     log("商店界面")
    // if (prudcuts_list()){
    //     getOne()
    // }
// }

while (true){
    try {
        log('等待加载')
        if (prudcuts_list()) {
            if (getOne()) {
                back()
                sleep(2000)
            }
        }
    } catch (error) {
        sleep(10 * 1000)
    }
}

// getOne()

// 15197543415
// getOne()


// printAll()



